#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @Version : Python-
# @Author  : Shengji He
# @Email   : hsjbit@163.com
# @File    : InvertBinaryTree.py
# @Time    : 2020/9/16 9:51
# @Description:


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        """
        Invert a binary tree.

        Example:

        Input:
                 4
               /   \
              2     7
             / \   / \
            1   3 6   9
        Output:
                 4
               /   \
              7     2
             / \   / \
            9   6 3   1

        :param root:
        :return:
        """

        if not root:
            return root
        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left, root.right = right, left
        return root

    def invertTree2(self, root: TreeNode) -> TreeNode:
        queue = [root]
        while len(queue):
            node = queue.pop(0)
            if node:
                node.left, node.right = node.right, node.left
                queue.append(node.left)
                queue.append(node.right)
        return root


if __name__ == '__main__':
    S = Solution()
    root = TreeNode(4)
    root.left = TreeNode(2)
    root.right = TreeNode(7)
    root.left.left = TreeNode(1)
    root.left.right = TreeNode(3)
    root.right.left = TreeNode(6)
    root.right.right = TreeNode(9)
    S.invertTree(root)
    S.invertTree2(root)
    print('done')
